package xx.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xx.services.Page;

public class HtmlFilter implements Filter
{
    Map<String, String> headers = new HashMap<String, String>();

    Set<String> names = new HashSet<String>();

    public void destroy()
    {
        headers.clear();
        names.clear();
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException
    {
        // 不要包含context-path
        HttpServletRequest request = (HttpServletRequest) req;
        String uriPattern = request.getServletPath();
        if (request.getPathInfo() != null)
            uriPattern = uriPattern + request.getPathInfo();

        HttpServletResponse response = (HttpServletResponse) res;
        for (Iterator it = headers.entrySet().iterator(); it.hasNext();)
        {
            Map.Entry entry = (Map.Entry) it.next();
            response.addHeader((String) entry.getKey(), (String) entry.getValue());
        }
        
        //if (!isExclude(uriPattern) && uriPattern.matches("/(\\w+|index|default).(html?|[ja]sp|php)$"))
        if(!isExclude(uriPattern) && uriPattern.matches("(.*).xhtml"))
        {
            Page page = new Page(req, res);
            page.go();
            return;
        }
        else
        {
            chain.doFilter(req, res);
        }
    }

    private boolean isExclude(String uri)
    {
        for (Iterator it = names.iterator(); it.hasNext();)
        {
            String name = "" + it.next();
            if (uri.indexOf(name) == 0)
            {
                return true;
            }
        }
        return false;
    }

    public void init(FilterConfig config) throws ServletException
    {
        String namesStr = config.getInitParameter("names");
        String[] names = namesStr.split(",");
        for (int i = 0; i < names.length; i++)
        {
            this.names.add(names[i].trim());
        }

        String headersStr = config.getInitParameter("headers");
        String[] headers = headersStr.split(";");
        for (int i = 0; i < headers.length; i++)
        {
            int equal = headers[i].indexOf("=");
            this.headers.put(headers[i].substring(0, equal), headers[i].substring(equal + 1));
        }
    }
}
